import base64
import random
from io import BytesIO

from flask_restful import Resource, reqparse
import requests
import json
from huiyan.extions import cache
from aip import AipOcr


""" 你的 APPID AK SK """
APP_ID = '34471333'
API_KEY = 'tRRFig9yS04B0seyzss4n1BV'
SECRET_KEY = 'GuoiGa8yatxvLOL9FVNbjrPgiNCGD5l3'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

# 参数解析
parser = reqparse.RequestParser()
parser.add_argument('image', type=str, default='')
parser.add_argument('type', type=str, default='base64')

# 百度OCR
class baiduAPI(Resource):
    def post(self):
        args = parser.parse_args()
        image: str = args.get('image')
        type: str = args.get('type')

        # 如果有可选参数
        options = {}
        options["language_type"] = "CHN_ENG"
        options["detect_direction"] = "true"
        options["detect_language"] = "true"
        options["probability"] = "true"

        # 判断图片还是Base64数据
        if type == "base64":
            # 调用通用文字识别（高精度版）
            image = image.replace("data:image/png;base64,", "")
            image = image.replace("data:image/jpeg;base64,", "")
            res_image = client.basicGeneral(base64.b64decode(image), options)
        else:
            # 调用通用文字识别（高精度版）
            res_image = client.basicGeneralUrl(image, options)


        return res_image


